package utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Description:Jedis连接池
 * @Author one world
 * @Date 2020/9/17 0017 12:55
 */
public class JedisPoolUtil {
    private static JedisPool pool = null;
    private static final Logger logger = LoggerFactory.getLogger(JedisPoolUtil.class);
    static {
        //加载配置文件
        InputStream in = JedisPoolUtil.class.getClassLoader().getResourceAsStream("redispool.properties");
        Properties pro = new Properties();
        try {
            pro.load(in);
        } catch (IOException e) {
            logger.error("加载Redis文件异常",e);
        }
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        //最大连接数
        poolConfig.setMaxTotal(Integer.parseInt( pro.get("redis.maxTotal").toString()));
        //最大空闲连接数
        poolConfig.setMaxIdle(Integer.parseInt( pro.get("redis.maxIdle").toString()));
        //最小空闲连接数
        poolConfig.setMinIdle(Integer.parseInt( pro.get("redis.minIdle").toString()));
        pool = new JedisPool(poolConfig, pro.get("redis.url").toString(),Integer.parseInt( pro.get("redis.port")
                .toString()),2000,pro.get("redis.password").toString());
    }

    /**
     * 获取Jdeis连接
     * @return
     */
    public static Jedis getJedis(){
        return pool.getResource();
    }

    /**
     * 释放Jedis连接
     * @param jedis
     */
    public static void release(Jedis jedis){
        if(null != jedis){
            jedis.close();
        }
    }
}
